const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  try {
    const {
      title,
      timeRange,
      ingredients,
      images,
      createTime
    } = event

    // 数据验证
    if (!title || !timeRange || timeRange.length !== 2) {
      return {
        success: false,
        error: '缺少必要信息'
      }
    }

    // 添加记录
    const result = await db.collection('cooking').add({
      data: {
        title,
        timeRange,
        ingredients,
        images,
        openid: wxContext.OPENID,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    })

    return {
      success: true,
      data: result._id
    }

  } catch (err) {
    console.error('[saveCookingRecord] 错误:', err)
    return {
      success: false,
      error: err.message
    }
  }
} 